const express = require('express')
const opn = require('opn')
// const debug = require('debug')('mydebug:http')
const log4js = require('log4js')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const session = require('express-session')
// const RedisStore = require('connect-redis')(session)
// const MongoStore = require('connect-mongo')(session)
// const MySQLStore = require('express-mysql-session')(session)
const { isProd, useOpn, host, port } = require('./config/sys.config')
const router = require('./router')

let app = express()
if (!isProd) {
  const webpack = require('webpack')
  const webpackDevMiddleware = require('webpack-dev-middleware')
  const webpackHotMiddleware = require('webpack-hot-middleware')
  const config = require('./build/webpack.dev.conf')
  let compiler = webpack(config)

  app.use(webpackDevMiddleware(compiler, {
    // noInfo: true,
    publicPath: config.output.publicPath,
    quiet: true
    // stats: {
    //   colors: true
    // }
  }))
  app.use(webpackHotMiddleware(compiler))
}

// log4js.addLayout('json', config => function (logEvent) {
//   return JSON.stringify(logEvent) + config.separator;
// })
log4js.configure('./log.config.json')
// app.use(log4js.connectLogger(log4js.getLogger(isProd ? 'request' : ''), {level: "auto", format: '[:remote-addr :method :url :status :response-timems][:referrer HTTP/:http-version :user-agent]'}))

// app.use('/static', express.static('./dist/static'))
app.set('views', './dist')
app.set('view engine', 'html')
app.engine('html', require('ejs').renderFile)

app.use(bodyParser.json()) // 解析contentType为application/json提交的数据（前端提交的数据需要反序列化JSON.stringify）
app.use(bodyParser.urlencoded({ // 解析contentType为application/x-www-form-urlencoded（表单）提交的数据
  extended: false
}))
// app.use(cookieParser()) // 不使用签名
app.use(cookieParser('zcl')) // 使用签名(需要设置{signed: true})
app.use(session({
  // store: new RedisStore({
  //   host: "localhost",
  //   port: 6379,
  //   db: 0,
  //   ttl : 1000
  // }), // 需要配置reids服务器
  // store: new MongoStore({
  //   url: 'mongodb://localhost/express',
  //   collection: 'sessions',
  //   ttl: 14 * 24 * 60 * 60 // = 14 days. Default
  // }), // 需要配置mongodb
  // store: new MySQLStore({
  //   host: 'localhost',
  //   port: 3306,
  //   user: 'root',
  //   password: '12345',
  //   database: 'db_test1'
  // }),
  secret: 'zcl', // 对session id 相关的cookie 进行签名
  name: 'sid', // 这里的name值得是传递sessionid的cookie的name，默认是：connect.sid
  // 设置maxAge是80000ms，即80s后session和相应的cookie失效过期
  cookie: {
    domain: 'localhost',
    maxAge: 80000
  },
  resave: true, // 是指每次请求都重新设置session cookie，假设你的cookie是10分钟过期，每次请求都会再设置10分钟
  saveUninitialized: true // 是指无论有没有session cookie，每次请求都设置个session cookie ，默认给个标示为 connect.sid
}))
app.use(router)

app.listen(port, host, () => {
  console.log('server starting at http://%s:%s', host, port)
  if (useOpn && !isProd) opn('http://' + host + ':' + port, {app: 'chrome'})
})
